<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>2007. 从双倍数组中还原原数组</title>
</head>

<body>
    <script>
        /**
         * @param {number[]} changed
         * @return {number[]}
         */
        var findOriginalArray = function(changed) {
            if (changed.length % 2 !== 0) {
                return []
            }
            changed.sort((a, b) => a - b)
                // 新建一个数组用于存放结果

            const count = {};
            for (const num of changed) {
                count[num] = (count[num] || 0) + 1;
            }
            const ans = new Array()
            for (const a of changed) {
                if (count[a] === 0) {
                    continue;
                }
                count[a]--;
                if (!count[a * 2]) {
                    return [];
                }
                count[a * 2]--;
                ans.push(a);
            }
            return ans;
        };

        let a = [2, 2, 1, 1]
        findOriginalArray(a)
    </script>
</body>

</html>